package com.atguigu.serviceedu.controller;


import com.atguigu.commonutils.R;
import com.atguigu.serviceedu.entity.EduChapter;
import com.atguigu.serviceedu.entity.vo.ChapterVo;
import com.atguigu.serviceedu.service.EduChapterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 课程 前端控制器
 * </p>
 *
 * @author testjava
 * @since 2020-07-08
 */
@RestController
@RequestMapping("/serviceedu/chapter")
//@CrossOrigin
public class EduChapterController {

    @Autowired
    private EduChapterService chapterService;

    /**
     * 把章节信息和小节信息封装后统一返回
     * 通过课程id进行查询
     */
    @GetMapping("getAllChapter/{courseId}")
    public R getAllChapter(@PathVariable("courseId") String courseId) {

        List<ChapterVo> list = chapterService.getAllChapter(courseId);
        return R.ok().data("allChapter", list);
    }

    //新增章节
    @PostMapping("addChapter")
    public R addChapter(@RequestBody EduChapter eduChapter) {
        chapterService.save(eduChapter);
        return R.ok();
    }

    //修改
    //1、查询
    @GetMapping("findChapterById/{chapterId}")
    public R findChapterById(@PathVariable("chapterId") String chapterId) {
        EduChapter eduChapter = chapterService.getById(chapterId);
        return R.ok().data("eduChapter", eduChapter);
    }

    //2、修改
    @PostMapping("updateChapter")
    public R updateChapter(@RequestBody EduChapter eduChapter) {
        chapterService.updateById(eduChapter);
        return R.ok();
    }

    /**
     * 删除章节
     * 如果章节下面有小节就不允许删除
     */
    @DeleteMapping("deleteChapter/{chapterId}")
    public R deleteChapter(@PathVariable("chapterId") String chapterId) {
        //删除前根据章节id查询该章节是否有小节
        boolean flag = chapterService.getChapterNumByChpterId(chapterId);
        if(flag)return R.ok();
        else return R.error();
    }


}

